import * as vscode from 'vscode';
import * as path from 'path';
import * as fs from 'fs';
import { spawn, ChildProcess } from 'child_process';

export interface ServerStatusCallback {
    (status: 'stopped' | 'running'): void;
}

export class ServerManager {
    private jgeProcess: ChildProcess | null = null;
    private outputChannel: vscode.OutputChannel;
    private statusCallback: ServerStatusCallback;
    private statusBarItem: vscode.StatusBarItem;

    constructor(outputChannel: vscode.OutputChannel, statusCallback: ServerStatusCallback) {
        this.outputChannel = outputChannel;
        this.statusCallback = statusCallback;
        
        // 创建状态栏项
        this.statusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 100);
        this.updateStatusBar('stopped');
    }

    public startServer(): void {
        const workspaceFolders = vscode.workspace.workspaceFolders;
        if (!workspaceFolders) {
            vscode.window.showErrorMessage('请先打开一个工作区');
            return;
        }

        const rootPath = workspaceFolders[0].uri.fsPath;
        const jgePath = path.join(rootPath, 'JGE-RS.exe');

        if (!fs.existsSync(jgePath)) {
            vscode.window.showErrorMessage('未找到JGE-RS.exe文件，请确保JGE-RS.exe位于工作区根目录');
            return;
        }

        this.statusCallback('running');
        this.outputChannel.clear();
        this.outputChannel.show();

        try {
            this.jgeProcess = spawn(jgePath, [], {
                cwd: rootPath,
                stdio: ['pipe', 'pipe', 'pipe']
            });

            this.jgeProcess.stdout?.on('data', (data) => {
                const message = data.toString();
                this.outputChannel.append(message);
                this.statusCallback('running');
            });

            this.jgeProcess.stderr?.on('data', (data) => {
                const message = data.toString();
                this.outputChannel.append('[ERROR] ' + message);
            });

            this.jgeProcess.on('close', (code) => {
                this.outputChannel.appendLine(`JGE进程已退出，退出码: ${code}`);
                this.jgeProcess = null;
                this.statusCallback('stopped');
            });

            this.jgeProcess.on('error', (err) => {
                this.outputChannel.appendLine(`启动JGE失败: ${err.message}`);
                this.jgeProcess = null;
                this.statusCallback('stopped');
                vscode.window.showErrorMessage(`启动JGE失败: ${err.message}`);
            });

        } catch (error) {
            this.statusCallback('stopped');
            vscode.window.showErrorMessage(`启动JGE时发生错误: ${error}`);
        }
    }

    public stopServer(): void {
        if (this.jgeProcess) {
            this.statusCallback('stopped');
            this.jgeProcess.kill('SIGTERM');
            
            // 如果进程没有正常退出，强制终止
            setTimeout(() => {
                if (this.jgeProcess && !this.jgeProcess.killed) {
                    this.jgeProcess.kill('SIGKILL');
                }
            }, 5000);
            
            this.jgeProcess = null;
            this.outputChannel.appendLine('JGE进程已停止');
        }
    }

    public toggleServer(): void {
        if (this.jgeProcess && !this.jgeProcess.killed) {
            this.stopServer();
        } else {
            this.startServer();
        }
    }

    public isRunning(): boolean {
        return this.jgeProcess !== null && !this.jgeProcess.killed;
    }

    public dispose(): void {
        this.stopServer();
        this.statusBarItem.dispose();
    }

    private updateStatusBar(status: 'stopped' | 'running'): void {
        switch (status) {
            case 'running':
                this.statusBarItem.text = "$(play) JGE Server 运行中";
                this.statusBarItem.tooltip = "JGE服务端正在运行";
                break;
            default: // stopped
                this.statusBarItem.text = "$(stop) JGE Server 已停止";
                this.statusBarItem.tooltip = "JGE服务端已停止";
        }
        this.statusBarItem.show();
    }
}
